package com.ld.front.util.notice;

import java.io.File;
import java.net.URL;
import java.util.List;

import org.apache.commons.mail.EmailAttachment;
import org.springframework.web.multipart.MultipartFile;

import com.ld.shieldsb.common.core.collections.ListUtils;
import com.ld.shieldsb.common.core.io.FileUtils;
import com.ld.shieldsb.common.core.model.Result;
import com.ld.shieldsb.common.core.util.PathUtil;
import com.ld.shieldsb.common.core.util.StringUtils;
import com.ld.shieldsb.common.core.util.notice.mail.EmailInfo;
import com.ld.shieldsb.common.core.util.notice.mail.EmailUtil;
import com.ld.shieldsb.common.core.util.notice.sms.SMSUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class NoticeSendUtil {

    /**
     * 发送邮件（带附件）
     * 
     * @Title sendEmail
     * @author 吕凯
     * @date 2019年6月28日 下午1:38:00
     * @param mailFromName
     * @param emailTo
     * @param subject
     * @param content
     * @param files
     * @param attachUrls
     * @return Result
     */
    public static Result sendEmail(String mailFromName, String emailTo, String subject, String content, MultipartFile[] files,
            String[] attachUrls) {
        EmailInfo mailInfo = new EmailInfo();
        mailInfo.addToAddress(emailTo);
        mailInfo.setSubject(subject);
        mailInfo.setContent(content);
        mailInfo.setFromName(mailFromName);

        // 本地附件
        if (files != null && files.length > 0) {
            for (int i = 0; i < files.length; i++) {
                MultipartFile file = files[i];
                String dir = PathUtil.getTmpDir() + "/emailfile/";

                String trueFileName = file.getOriginalFilename(); // 原文件名
                String suffix = trueFileName.substring(trueFileName.lastIndexOf("."));
                String fileName = System.currentTimeMillis() + "_" + StringUtils.getRandomNum(3) + suffix; // 生成文件名
                log.warn(dir);
                File targetFile = new File(dir, fileName);
                if (!targetFile.getParentFile().exists()) { // 上级目录不存在则级联创建
                    targetFile.getParentFile().mkdirs();
                }
                // 保存
                try {
                    file.transferTo(targetFile);
                } catch (Exception e) {
                    log.error("", e);
                }
                if (file != null) {
                    EmailAttachment att = new EmailAttachment();
                    att.setPath(targetFile.getAbsolutePath()); // 本地存在的文件
                    att.setName(trueFileName);
                    att.setDescription("附件");
                    mailInfo.addAttachments(att);
                }
            }
        }

        // 远程附件
        if (attachUrls != null && attachUrls.length > 0) {
            for (int i = 0; i < attachUrls.length; i++) {
                EmailAttachment attUrl = new EmailAttachment();
                try {
                    attUrl.setURL(new URL(attachUrls[i])); // 远程地址
                    attUrl.setName("附件" + i + "." + FileUtils.getFileExtension(attachUrls[i]));
                    attUrl.setDescription("附件" + i);
                    mailInfo.addAttachments(attUrl);
                } catch (Exception e) {
                    log.error("", e);
                }
            }
        }

        Result result = EmailUtil.sendEmail(mailInfo);
        // 删除本地附件
        List<EmailAttachment> attachments = mailInfo.getAttachments();
        if (ListUtils.isNotEmpty(attachments)) {
            attachments.forEach(attachment -> {
                if (StringUtils.isNotBlank(attachment.getPath())) {
                    FileUtils.deleteFile(attachment.getPath());
                }
            });
        }
        return result;
    }

    /**
     * 发送短信
     * 
     * @Title sendSMS
     * @author 吕凯
     * @date 2019年7月1日 下午4:33:36
     * @param phoneNum
     * @param message
     * @param signName
     * @return SMSResult
     */
    public static Result sendSMS(String phoneNum, String message, String signName) {
        if (message.length() > 200) { // 字数太多进行截取
            message = message.substring(0, 200) + "……";
        }
        if (StringUtils.isBlank(signName)) {
            signName = "绿盾项目组";
        }
        Result smsResult = SMSUtil.sendSMS(-1, phoneNum, message, signName, false);
        log.warn((smsResult != null ? smsResult.getSuccess() : false) + "");
        return smsResult;

    }

}
